package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.impl.MessageServiceImpl;
import com.example.forum.services.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-09-28
 * Time: 9:26
 */

@Api(tags = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private MessageServiceImpl messageService;
    @Resource
    private UserServiceImpl userService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收用户id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("站内信内容") @RequestParam("content") @NonNull String content) {
        // 从 session 中获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 检查用户状态 -- 是否禁言
        if (user.getState() != 0) {
            // 打印日志
            log.warn("检测到用户尝试在禁言状态下发送站内信 -- user id = " + user.getId());
            // 返回结果
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        // 不能给自己发站内信
        if (user.getId() == receiveUserId) {
            // 打印日志
            log.warn("发送站内信失败 -- 尝试自己给自己发送站内信, user id = " + user.getId());
            // 返回结果
            return AppResult.fail("不能给自己发送站内信");
        }
        // 根据 receiveUserId 查询数据库
        User selectUser = userService.selectById(receiveUserId);
        if (selectUser == null || selectUser.getDeleteState() != 0) {
            // 打印日志
            log.warn("检测到非法访问 -- 发送站内信时提供的 receiveUserId 无效,receiveUserId = " + receiveUserId);
            // 返回结果
            return AppResult.fail(ResultCode.FAILED);
        }
        // 构造站内信
        Message insertMessage = new Message();
        insertMessage.setPostUserId(user.getId());
        insertMessage.setReceiveUserId(receiveUserId);
        insertMessage.setContent(content);
        // 调用 service 层
        messageService.create(insertMessage);
        // 打印日志
        log.info("用户发送站内信成功," + insertMessage);
        return AppResult.success();
    }

    /**
     * 获取未读消息个数
     *
     * @param request
     * @return
     */
    @ApiOperation("获取未读消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult getUnreadCount(HttpServletRequest request) {
        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 调用 service 层
        int count = messageService.selectUnreadCount(user.getId());
        // 返回结果
        return AppResult.success(count);
    }

    /**
     * 查询登录用户的所有站内信
     *
     * @return
     */
    @ApiOperation("查询登录用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult getAll(HttpServletRequest request) {
        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 调用 service 层,获取站内信
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        // 返回结果
        return AppResult.success(messages);
    }

    /**
     * 更新站内信状态为已读
     *
     * @param id 站内信Id
     * @return AppResult<Message>
     */
    @ApiOperation("更新状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam(value = "站内信Id") @RequestParam(value = "id") @NonNull Long id) {
        // 验证站内信id的真实性
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() != 0) {
            // 打印日志
            log.warn("检测到非法访问 -- 用户尝试修改不存在或已被删除的站内信的状态,message id = " + id);
            // 返回结果
            return AppResult.fail(ResultCode.FAILED);
        }
        // 验证站内信的接受者是否是当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (message.getReceiveUserId() != user.getId()) {
            // 打印日志
            log.warn("检测到非法访问 -- 用户尝试修改接收者不为他的站内信");
            // 返回结果
            return AppResult.fail(ResultCode.FAILED);
        }
        // 调用 service 层,更新数据库
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    /**
     * 回复站内信
     *
     * @param repliedId 要回复的站内信Id
     * @param content   站内信的内容
     * @return
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content) {
        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 检查当前用户是否为禁言状态
        if (user.getState() != 0) {
            // 打印日志
            log.warn("检测到用户尝试在禁言状态下回复站内信 -- user id = " + user.getId());
            // 返回结果
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        // 验证 repliedId 的真实性
        Message message = messageService.selectById(repliedId);
        if (message == null || message.getDeleteState() != 0) {
            // 打印日志
            log.warn("检测到非法访问 -- 用户尝试回复不存在或已被删除的站内信的状态,repliedId = " + repliedId);
            // 返回结果
            return AppResult.fail(ResultCode.FAILED);
        }
        // 验证要回复的站内信的接收者是否是当前登录用户
        if (message.getReceiveUserId() != user.getId()) {
            // 打印日志
            log.warn("检测到非法访问 -- 用户尝试修改接收者不为他的站内信");
            // 返回结果
            return AppResult.fail(ResultCode.FAILED);
        }
        // 构造对象
        Message insertMessage = new Message();
        insertMessage.setPostUserId(user.getId());
        insertMessage.setReceiveUserId(message.getPostUserId());
        insertMessage.setContent(content);
        // 调用 service 层
        messageService.reply(repliedId, insertMessage);
        return AppResult.success();
    }
}
